import fs from 'fs';
import Koa from 'koa';
import Router from '@koa/router';
import cors from '@koa/cors';
import staticServer from 'koa-static';
import koaRange from 'koa-range';
import {koaBody} from 'koa-body';
import jwt from 'jsonwebtoken';
import response from './response.js';
import compress from 'koa-compress'; //gzip支持
import conditional from 'koa-conditional-get'; //协商缓存支持
import etag from 'koa-etag'; //协商缓存支持

const authWhiteList = ['/api/business/login', '/slb/check', '/View/', '/api/merchant/login'];
const tokenSecret = '1234567890';

class WebServer {
    constructor() {
        this.port = 80;
        this.app = null;
        this.router = null;
    }

    async  auth(ctx, next) {
        const url = ctx.url;
        console.log(url);   
        // 登录验证白名单
        let isWhiteListed = authWhiteList.some((path) => url.startsWith(path));
        if (isWhiteListed) {
            await next();
            return;
        }
    
        // 登录验证
        let token = ctx.header.token || '';
        try {
            let obj = jwt.verify(token, tokenSecret);
            ctx.state.oper = obj;
        } catch (err) {
            ctx.body = response.fail('token验证失败');
            return;
        }
        await next();
    }
    

    async Start(port, routerPath = './Services') {
        if (port != null) {
            this.port = port;
        }
        this.app = new Koa();
        this.router = new Router();
        //加载所有服务路由
        let fileList = fs.readdirSync(routerPath);
        for (const file of fileList) {
            try {
                let result = await import(`${routerPath}/${file}`);
                this.router.use(result.router.routes());
            } catch (err) {
                console.error(`注册路由失败,文件名:${file}`, err);
            }
        }
        //启动web服务
        this.app.use(async (ctx, next) => { //错误捕获
            try {
                await next();
            } catch (error) {
                ctx.status = error.statusCode || error.status || 500;
                ctx.body = error.message;
                console.trace(error);
            }
        })
        this.router.all('/slb/check', async (ctx) => {
            ctx.body = 'ok';
        });
        this.app.use(this.auth);
        this.app.use(cors());
        this.app.use(koaRange);
         this.app.use(conditional());
        this.app.use(etag());
        this.app.use(compress());
        this.app.use(staticServer('./View'));
       this.app.use(
            koaBody({
                multipart: true,
                formidable: {
                    maxFieldsSize: 500 * 1024 * 1024, // 最大文件大小为 500MB
                    multipart: true,
                    keepExtensions: true, // 保持原始文件的扩展名
                },
            })
        );
        this.app.use(this.router.routes());
        this.app.use(this.router.allowedMethods()); //ctx.status为空或者404的时候,丰富response对象的header头
        this.app.listen(this.port, () => {
            console.log(`web服务启动成功,端口:${this.port}`);
        });
    }
}

export default WebServer;
